-- UICarriableItem
-- Create by zouyb
-- 试剂选择界面

require "game/ui/form/artifact/UIArtifactRepair"
require "game/ui/form/reagent/UIReagent"

-- UICarriableItem继承自Layer
UICarriableItem = class("UICarriableItem", function()
    return cc.Layer:create();
end);

function UICarriableItem.create()
    return UICarriableItem.new();
end

-- 最大行数
local MIN_GRID_COLUMN = 4;
local MAX_GRID_ROW    = 2;
local ITEM_NAME       = "artifact";
-- 内部函数声明

-- 构造函数
function UICarriableItem:ctor(id)
    -- 初始化
    self:setName("UICarriableItem");
    local node = cc.CSLoader:createNode("layout/lictor/LictorChoose.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    self.CT = CT;
    local scroll_view = findChildByName(self.node, "CT/bg_1/scroll_view");
    self.scrollView = scroll_view;

    self.selectIndex = 1;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    self:initData();

    self:initGrids();
    -- 重绘
    self:redraw();

    -- 适配
    self:resize();

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UICarriableItem 界面析构清理");
            EventMgr.removeAll("UICarriableItem");

            local UIEnterDungeon = UIMgr.getCurrentScene():getFormByName("UIEnterDungeon");
            if UIEnterDungeon then
                UIEnterDungeon:setVisible(true);
            end
        elseif ev == "enter" then
            local UIEnterDungeon = UIMgr.getCurrentScene():getFormByName("UIEnterDungeon");
            if UIEnterDungeon then
                UIEnterDungeon:setVisible(false);
            end
        end
    end);
end

-- 适配
function UICarriableItem:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

local function sortItem(item1, item2)
    if item1.rank <  item2.rank then
        return true;
    elseif item1.rank >item2.rank then
       return false
    end

    if item1.classId < item2.classId then
        return true;
    else
        return false;
    end
end

function UICarriableItem:initData()
    self.data = {};
    local hasCarriaItems = ItemM.getItemsByGroup(ME.user, 27);
    local info = {};

    for i = 1, #hasCarriaItems, 1 do
        info = ItemM.query(hasCarriaItems[i]);
        local item = {};
        item.name = info.name;
        item.rank = info.rank;
        item.desc = ItemM.getItemDesc(hasCarriaItems[i]);
        item.detail = ItemM.getItemDetail(hasCarriaItems[i]);
        item.count = ItemM.getOwnedAmount(ME.user, hasCarriaItems[i]);

        item.classId = info.class_id;
        item.isHas = true; -- 是否已经拥有

        table.insert(self.data,item);
    end

    -- 对英雄进行排序
    table.sort(self.data, sortItem);

end

-- 初始化格子
function UICarriableItem:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 10;

    -- 图标间距(纵向)
    local hGap = 23;

    -- 图标宽度
    local iconWidth = 110;

    -- 图片高度
    local iconHeight = 115;

    local topHGap  = 3;
    local leftWGap = 20;
    local bottomHGap = 50;

    -- 收集扈从信息
    local lictorsList = self.data;

    -- 扈从的总个数
    local lictorCount = #lictorsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/artifactt/ArtifactChooseItem.csb");
    itemNode:setScale(0.88);
    -- 初始化滚动容器内的单元格（仅针对竖向滚动容器）
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param pageRowNum    单页可以显示下的行数
    -- @param maxColNum     最大列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留白
    -- @param bottomHGap    下方留白
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, lictorCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerCarriableItemTouchEvent);
end

-- 显示神器选择界面
function UICarriableItem:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title/title_label");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("carriable_item"));

    -- 绘制副标题
    local titleExplainLabel = findChildByName(self.CT, "title/title_explain");
    titleExplainLabel:setString(getLocStr("can_carry_count"));
    TextStyleM.setSubheadStyle(titleExplainLabel);

    -- 隐藏阵营相关信息
    local campIcon = findChildByName(self.CT, "bg_2/camp_icon");
    campIcon:setVisible(false);

    local campLabel = findChildByName(self.CT, "bg_2/camp_label");
    campLabel:setVisible(false);

    -- 收集信息
    local totalGridCount = #self.data;

    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, self.data[i]);
        end
    end

    -- 初始化神器说明
    if #self.data > 0 then
      self:artifacttSelected(self.selectIndex, self.selectIndex);
    else
        local captionLabel = findChildByName(self.CT, "bg_2/caption_label");
        captionLabel:setVisible(true);
        TextStyleM.setTextStyle(captionLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        applyString(captionLabel, getLocStr("modulation_reagent"));

        local explainText = "";
        local explainLabel = findChildByName(self.CT, "bg_2/explain_scroll/explain");
        explainLabel:setVisible(true);
        TextStyleM.setTextStyle(explainLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
        explainLabel:setString(getLocStr("dont_has_item"));

        local btnSelect = findChildByName(self.node, "BT/choose_btn");
        btnSelect:setTouchEnabled(false);
        btnSelect:setBright(false);
    end
end

--  初始化格子信息
function UICarriableItem:initGridInfo(grid, data)

    local explainText = grid:getChildByName("explain");
    local str = "";

    local numLabel = grid:getChildByName("level_label");
    TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    -- 显示试剂icon
    local iconImage = grid:getChildByName("icon");
    local iconIndex = ItemM.query(data.classId, "icon");
    iconImage:loadTexture(getItemIconPath(iconIndex));
    iconImage:setVisible(true);

    local bgImg = grid:getChildByName("bg");
    bgImg.classId = data.id;

    if data.isHas then
        bgImg:setVisible(true);
        numLabel:setVisible(true);

       local carriableCount = FormulaM.invoke("CALC_DUNGEON_ITEM_MAX_AMOUNT", data.classId);
       local amount = data.count;
       numLabel:setString(amount);
       if amount < carriableCount then
           TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_DARK_RED, true);
       end
   end

   local starImage = grid:getChildByName("star_2");
   starImage:setVisible(true);
   local tStar = createStarLayer(data.rank,"images/ui/symbol/star_little.png", "center", -0.7);
   if tStar then
         starImage:removeAllChildren();
         starImage:addChild(tStar);
   end
end

-- 注册商品点击事件
function UICarriableItem:registerCarriableItemTouchEvent(node)
    -- 注册商品图标点击事件
    local bg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if self.data[node.index] == nil then
                return;
            end
            local lastSelected = self.selectIndex;

            self.selectIndex = node.index;

            self:artifacttSelected(lastSelected, node.index);
        end
    end
    bg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UICarriableItem:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UICarriableItem");
        elseif eventType == "enter" then

        end
    end);

    -- 关注购买商品的事件
    EventMgr.register("UICarriableItem", event.REAGENT_BUY_GOODS, function(args)
        self:initData();
        self:initGrids();

        for i = 1, #self.data do
            if self.data[i].classId == args.classId then
                self.selectIndex = i;
            end
        end
        self:redraw();
    end);
end

-- 注册点击事件
function UICarriableItem:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UICarriableItem");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册选择按钮点击事件
    local btnSelect = findChildByName(self.node, "BT/choose_btn");
    local function onSelectClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local data = self.data[self.selectIndex];
            local carriableCount = FormulaM.invoke("CALC_DUNGEON_ITEM_MAX_AMOUNT", data.rank);
            local amount = math.min(data.count, carriableCount);
            if not ItemM.canCarryDungeonItem(data.classId, amount) then
                return;
            end
            local args = {["classId"]=data.classId, ["amount"] = amount}
            EventMgr.fire(event.ITEM_CHOOSE_OK, args);

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UICarriableItem");
        end
    end
    btnSelect:addTouchEventListener(onSelectClick);
    TextStyleM.setTextStyle(btnSelect, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnSelect:setTitleText(getLocStr("btn_text_select"));

    -- 注册购买按钮点击事件
    local btnBuy = findChildByName(self.node, "BT/repair_btn");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local uiReagent = UIReagent.create();
            UIMgr:getCurrentScene():addForm(uiReagent);
            AudioM.playFx("workshop_open_ui");
        end
    end
    btnBuy:setVisible(true);
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(getLocStr("btn_text_modulation"));
end

-- 神器选中效果
function UICarriableItem:artifacttSelected(lastSelected, nowSelected)
    -- 清除上次选中效果
    local lastSel = self.scrollView:getChildByName("item" .. lastSelected);
    local focusBg = lastSel:getChildByName("focus");
    focusBg:setVisible(false);

    -- 新选中的效果
    local nowSel = self.scrollView:getChildByName("item" .. nowSelected);
    local nowFocusBg = nowSel:getChildByName("focus");
    nowFocusBg:setVisible(true);

    -- 更新说明和按钮
    local data = self.data[nowSelected];
    self:refreshExplain();
    local btnSelect = findChildByName(self.node, "BT/choose_btn");
    if data.isHas then
        btnSelect:setBright(true);
        btnSelect:setTouchEnabled(true);
    else
        btnSelect:setBright(false);
        btnSelect:setTouchEnabled(false);
    end
end

-- 设置说明
function UICarriableItem:refreshExplain()

    -- 更新说明
    local data = self.data[self.selectIndex];

    -- 先把标题和描述隐藏起来
    local captionLabel = findChildByName(self.CT, "bg_2/caption_label");
    captionLabel:setVisible(false);
    local Label = findChildByName(self.CT, "bg_2/explain_scroll/explain");
    Label:setVisible(false);

    local durabilityLabel = findChildByName(self.CT, "bg_2/durability_label");
    durabilityLabel:setVisible(false);

    local scrapLabel = findChildByName(self.CT, "bg_2/scrap_label");
    scrapLabel:setVisible(false);

    local needScrapLabel = findChildByName(self.CT, "bg_2/need_scrap_label");
    needScrapLabel:setVisible(false);

    -- 阵营
    local campLabel = findChildByName(self.CT, "bg_2/camp_label");
    campLabel:setVisible(false);

    -- 隐藏阵营
    local campIcon = findChildByName(self.CT, "bg_2/camp_icon");
    campIcon:setVisible(false);

    -- 获取试剂名
    local artifactName = data.name;

    -- 显示试剂使用效果
    if data.isHas then
        captionLabel:setVisible(true);
        TextStyleM.setTextStyle(captionLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        applyString(captionLabel, artifactName);

        local explainText = "";
        local explainLabel = findChildByName(self.CT, "bg_2/explain_scroll/explain");
        explainLabel:setVisible(true);
        TextStyleM.setTextStyle(explainLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
        applyString(explainLabel, data.detail.."[red]\n\n"..getLocStr("carriable_item_tip").."[-]");

        -- 当前拥有的数量
        local amountLabel = findChildByName(self.CT, "bg_2/camp_label");
        local count = ItemM.getAmount(ME.user, data.classId);
        local str = getLocStr("carriable_item_amount");
        TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
        amountLabel:setVisible(true);
        applyString(amountLabel, string.format(str, count));
    end
end